package com.yixueyun.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixueyun.base.exception.CommonError;
import com.yixueyun.base.exception.YiXueYunPlusException;
import com.yixueyun.content.config.MultipartSupportConfig;
import com.yixueyun.content.feigncient.MediaServiceClient;
import com.yixueyun.content.mapper.CourseBaseMapper;
import com.yixueyun.content.mapper.CourseMarketMapper;
import com.yixueyun.content.mapper.CoursePublishMapper;
import com.yixueyun.content.mapper.CoursePublishPreMapper;
import com.yixueyun.content.model.dto.CourseBaseInfoDto;
import com.yixueyun.content.model.dto.CoursePreviewDto;
import com.yixueyun.content.model.dto.TeachplanDto;
import com.yixueyun.content.model.po.CourseBase;
import com.yixueyun.content.model.po.CourseMarket;
import com.yixueyun.content.model.po.CoursePublish;
import com.yixueyun.content.model.po.CoursePublishPre;
import com.yixueyun.content.service.CourseBaseInfoService;
import com.yixueyun.content.service.CoursePublishService;
import com.yixueyun.content.service.TeachplanService;
import com.yixueyun.messagesdk.model.po.MqMessage;
import com.yixueyun.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 课程发布接口实现
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    private CourseBaseInfoService courseBaseInfoService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    private CoursePublishMapper coursePublishMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private MediaServiceClient mediaServiceClient;

    /**
     * 课程预览信息汇总
     * @param courseId 课程id
     * @return
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        //查询课程基本信息，
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        //查询课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);

        return coursePreviewDto;
    }

    /**
     * 课程审核
     * @param companyId
     * @param courseId  课程id
     */
    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {
        //先查询课程
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if(courseBaseInfo == null) {
            YiXueYunPlusException.cast("课程不存在！");
        }
        Long companyId1 = courseBaseInfo.getCompanyId();
        if(!companyId1.equals(companyId)){
            YiXueYunPlusException.cast("该课程您没有权限");
        }
        //当课程状态为已提交，不允许提交；
        String auditStatus = courseBaseInfo.getAuditStatus();
        if (auditStatus.equals("202003")) {
            YiXueYunPlusException.cast("课程已提交，请等待课程审核通过");
        }
        //当课程信息不全，不允许提交
        String pic = courseBaseInfo.getPic();
        if(StringUtils.isEmpty(pic)) {
            YiXueYunPlusException.cast("请上传课程图片");
        }
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if (teachplanTree == null ||teachplanTree.size() == 0) {
            YiXueYunPlusException.cast("请先添加课程计划信息");
        }
        //将课程基本信息、课程计划等信息插入到预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //设置机构id
        coursePublishPre.setCompanyId(companyId);
        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        String jsonMarket = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(jsonMarket);
        //计划信息
        String teachplan = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplan);
        //已提交
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());
        //判断是更新操作还是插入操作
        CoursePublishPre coursePublishPre1 = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre1 == null) {
            //插入
            coursePublishPreMapper.insert(coursePublishPre);
        }else {
            //更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        //更新基本表中的状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * 课程发布
     * @param companyId
     * @param courseId
     */
    @Override
    @Transactional
    public void publish(Long companyId, Long courseId) {
        //查询预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        String status = coursePublishPre.getStatus();
        if(!status.equals("202004")) {
            YiXueYunPlusException.cast("课程审核不通过");
        }
        //将预发布表拷贝到发布表
        CoursePublish coursePublish = new CoursePublish();
        if(coursePublishPre == null) {
            YiXueYunPlusException.cast("课程未审核，不允许发布");
        }
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        if(coursePublishObj == null ) {
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }
        //将预发布表拷贝到消息表
        saveCoursePublishMessage(courseId);
        //删除预发布表数据
        coursePublishPreMapper.deleteById(courseId);
    }

    /**
     * 生成html文件
     * @param courseId  课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        File htmlFile = null;
        try {
            Configuration configuration = new Configuration(Configuration.getVersion());
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate("course_template.ftl");
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("model",coursePreviewInfo);
            //Template 模板 model 数据
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //使用流将html写入文件
            InputStream inputStream = IOUtils.toInputStream(html, "utf-8");
            htmlFile = File.createTempFile("coursepublish",".html");
            FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream,fileOutputStream);
        } catch (Exception e) {
            log.error("页面静态化出现问题，courseId:{}",courseId,e);
            e.printStackTrace();
        }
        return htmlFile;
    }

    /**
     * 上传minio
     * @param courseId
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {

        try {
            MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
            String upload = mediaServiceClient.upload(multipartFile, "course/"+courseId+".html");
            if(upload == null) {
                log.debug("远程调用走降级逻辑得到上传结果位位null，课程id：{}",courseId);
                YiXueYunPlusException.cast("上传静态文件异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            YiXueYunPlusException.cast("上传静态文件异常");
        }
    }

    /**
     * 根据课程id查询课程发布信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish ;
    }

    private void saveCoursePublishMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if(mqMessage == null) {
            YiXueYunPlusException.cast(CommonError.UNKOWN_ERROR);
        }

    }

}
